<template>
  <div class="chat-container">
    <iframe 
      src="http://localhost/chatbot/uibaZhy5lyo48nwp" 
      style="width: 100%; height: 100%; min-height: 700px" 
      frameborder="0" 
      allow="microphone"> 
    </iframe>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';

const inputText = ref('');
const messages = ref([]);
const apiKey = import.meta.env.VITE_OPENAI_API_KEY; // 从环境变量读取

async function sendMessage() {
  if (!inputText.value.trim()) return;
  
  // 添加用户消息
  messages.value.push({ text: inputText.value, sender: 'user' });
  const userInput = inputText.value;
  inputText.value = '';

  try {
    // 调用 OpenAI API
    const response = await axios.post(
      'https://api.openai.com/v1/chat/completions',
      {
        model: "gpt-3.5-turbo",
        messages: [{ role: "user", content: userInput }]
      },
      {
        headers: {
          'Authorization': `Bearer ${apiKey}`,
          'Content-Type': 'application/json'
        }
      }
    );
    
    // 添加 AI 回复
    const aiReply = response.data.choices[0].message.content;
    messages.value.push({ text: aiReply, sender: 'bot' });
    
  } catch (error) {
    console.error("API 请求失败:", error);
    messages.value.push({ text: "请求出错，请重试", sender: 'error' });
  }
}
</script>

<style scoped>
.chat-container {
  max-width: 600px;
  margin: 0 auto;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 20px;
}
.messages {
  height: 400px;
  overflow-y: auto;
  list-style: none;
  padding: 0;
}
.user { text-align: right; color: #1e88e5; }
.bot { text-align: left; color: #43a047; }
.input-area {
  display: flex;
  margin-top: 15px;
}
input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}
button {
  margin-left: 10px;
  padding: 10px 20px;
  background: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
}
</style>